package com.jayqqaa12.system.controller;

import com.jayqqaa12.common.Consts;
import com.jayqqaa12.jbase.jfinal.ext.ShiroExt;
import com.jayqqaa12.jbase.jfinal.ext.ctrl.JsonController;
import com.jayqqaa12.shiro.ShiroCache;
import com.jayqqaa12.system.model.Role;
import com.jayqqaa12.system.model.User;
import com.jayqqaa12.system.validator.RoleValidator;
import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.spring.Inject;

@ControllerBind(controllerKey = "/system/role")
public class RoleCtrl extends JsonController<Role> {

	@Inject.BY_TYPE
	Role roleDao;

	public void list() {
		renderJson(roleDao.list());
	}

	public void tree() {
		Integer pid = getParaToInt("id");
		Integer passId = getParaToInt("passId");
		renderJson(roleDao.getTree(pid, passId));

	}

	public void grant() {
		Role role = getModel();
		String res_ids = getPara("res_ids");
		renderJsonResult(roleDao.batchGrant(role.getId(), res_ids));

		ShiroCache.clearAuthorizationInfoAll();

	}

	@Before(value = { RoleValidator.class })
	public void save() {
		Role role = getModel();

		if (role.getId() != null) renderJsonResult(role.update());
		else renderJsonResult(role.save());

	}

	public void delete() {
		int id = getParaToInt("id");

		for (Role r : roleDao.getRole(((User) ShiroExt.getSessionAttr(Consts.SESSION_USER)).getId())) {
			if (r.getId() == id) {
				renderJsonError("无法删除 自己的角色");
				return;
			}
		}

		if (id == 1) renderJsonError("admin 无法删除");
		else renderJsonResult(roleDao.deleteByIdAndPid(id));
	}

}
